import re

from django.contrib import messages
from django.contrib.auth import authenticate
# from django.contrib.auth.models import User
from django.contrib.auth.views import login
from django.db import DatabaseError
from django.shortcuts import render, redirect, reverse
from django.views import View
from apps.user.models import User


class LoginView(View):
    """
    用户登录视图
    """
    def get(self, request):
        # 获取参数
        username = request.GET.get("username")
        password = request.GET.get('pass')
        remembered = request.GET.get('remembered')
        # 校验参数
        if not all([username, password]):
            return render(request, 'login.html')
        msg = None
        if not all([username, password]):
            return render(request, 'login.html')
        # 判断用户名是否是5-20个字符
        if not re.match(r'^[a-zA-Z0-9_-]{5,20}$', username):
            msg = '请输入正确的用户名或手机号'
            messages.success(request, msg)
            return render(request, 'login.html')
        #
        # 判断密码是否是8-20个数字
        if not re.match(r'^[0-9A-za-z]{8,20}$', password):
            msg = '密码在8-20个数字'
            messages.success(request, msg)
            return render(request, 'login.html')
        # 认证登录用户
        user = authenticate(username=username, password=password)
        if user is None:
            msg = '用户名或密码错误'
            messages.success(request, msg)
            return render(request, 'login.html')
        # 实现状态保持
        login(request, user)

        # 设置状态保持的周期
        if remembered != 'on':
            # 没有记住用户：浏览器会话终结
            request.session.set_expiry(0)

        else:
            # 记住用户，None表示两周后过期
            request.session.set_expiry(None)

        # 响应登录结果
        return redirect(reverse('index:index'))


class RegisterView(View):
    """
    注册视图
    """
    def get(self, request):
        # 获取参数
        username = request.GET.get('username')
        password = request.GET.get('pass')
        # 校验参数
        msg = None
        if not all([username, password]):
            return render(request, 'register.html')
        # 判断用户名是否是5-20个字符
        if not re.match(r'^[a-zA-Z0-9_-]{5,20}$', username):
            msg = '请输入正确的用户名或手机号'
            messages.success(request, msg)
            return render(request, 'register.html')
        #
        # 判断密码是否是8-20个数字
        if not re.match(r'^[0-9A-za-z]{8,20}$', password):
            msg = '密码在8-20个数字'
            messages.success(request, msg)
            return render(request, 'register.html')
        # 存入数据
        try:
            user = User.objects.create_user(username=username, password=password)
        except DatabaseError:
            msg = '注册失败'
            messages.success(request, msg)
            return render(request, 'register.html')
        # 实现状态保持

        login(request, user)
        response = redirect(reverse('index:index'))

        # 注册时用户名写入到cookie，有效期15天
        response.set_cookie('username', user.username, max_age=3600 * 24 * 15)
        msg = '注册成功'
        messages.success(request, msg)
        # 弹窗
        return response


class UserCenterView(View):
    """
    用户中心视图
    """
    def get(self, request):
        return render(request, 'user_center.html')